package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go-ecommerce/internal/service"
	"go-ecommerce/internal/utils"
	"gorm.io/gorm"
	"net/http"
	"strings"
)

// PermissionMiddleware 动态权限控制中间件
func PermissionMiddleware(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		adminIDStr, exists := c.Get("admin_id")
		if !exists {
			utils.Error(c, 401, "未登录")
			return
		}
		adminID := adminIDStr.(uint)
		// 查询权限
		permissions, err := service.GetAdminPermissions(db, adminID)
		if err != nil {
			utils.Error(c, http.StatusInternalServerError, "查询权限失败")
			c.Abort()
			return
		}
		fmt.Println("查询出来的权限------------", permissions)
		// 判断当前请求是否匹配权限
		method := c.Request.Method
		path := c.FullPath() // 获取注册时定义的路由，如 /admin/product/:id
		match := false

		for _, p := range permissions {
			// 如果权限的 method 和 path 与当前请求匹配
			if strings.EqualFold(p.Method, method) && strings.HasPrefix(path, p.Path) {
				match = true
				break
			}
		}

		if !match {
			utils.Error(c, http.StatusForbidden, "无权限访问该接口")
			c.Abort()
			return
		}

		c.Next()
	}
}
